<?php

namespace App\Http\Controllers\Web;

use App\ConstDir\ErrorConst;
use App\Repository\Models\Products;
use Illuminate\Http\Request;
use App\Repository\Repositories\Interfaces\ProductAttributesRepository;

 
class ProductAttributesController extends BaseController
{
    
    protected $product_attrs_repo;

    public function __construct(ProductAttributesRepository $product_attrs_repo)
    {
        $this->product_attrs_repo = $product_attrs_repo;
    }

    public function index(Request $request){
        $type = $request->get('type', 'page');
        if($type == 'page'){
            $skus = $this->product_attrs_repo->paginate($this->perPage);
            return $this->success(ErrorConst::SUCCESS_CODE_MSG, $skus, true);
        }elseif($type == 'all'){
            $skus = $this->product_attrs_repo->all();
            return $this->success(ErrorConst::SUCCESS_CODE_MSG, $skus['data']);
        }
    }

    public function show($prodcut_attrs_id){
        $product_info = $this->product_attrs_repo->find($prodcut_attrs_id);
        
        return $this->success(ErrorConst::SUCCESS_CODE, $product_info['data']);
    }
    
    public function getByProductId($product_id){
        $product_info = $this->product_attrs_repo->whereFirst(['product_id'=>$product_id]);
        return $this->success(ErrorConst::SUCCESS_CODE, $product_info['data']);
    }

    /**
    * 找资质首页 产品列表
    */
    public function qualifiedProduct(Request $request){
        $data=$request->all(['attributes2']);
        if(!empty($data['attributes2'])){
            $attributes=$data['attributes2'];
            $product=$this->product_attrs_repo->with(['product'=>function($sql){
                  $sql->select(['id','name','shop_id','first_cat','second_cat','third_cat','cover_image','shop_id']);
                     }])->whereHas('product',function($sql){
           $sql->where('second_cat',572)->where('status', Products::STATUS_CHECKED)->where('is_for_sale',Products::IS_FOR_SALE_YES)->where('product_type',Products::IS_QUALIFIED_TYPE);
              })->scopeQuery(function($product) use ($attributes){
                return $product->where('attributes','like', '%'.$attributes.'%');
            })->paginate($this->perPage);
        }else{

           $product=$this->product_attrs_repo->with(['product'=>function($sql){
                      $sql->select(['id','name','shop_id','first_cat','second_cat','third_cat','cover_image','shop_id']);
                         }])->whereHas('product',function($sql){
               $sql->where('second_cat',572)->where('status', Products::STATUS_CHECKED)->where('is_for_sale',Products::IS_FOR_SALE_YES)->where('product_type',Products::IS_QUALIFIED_TYPE);
                  })->paginate($this->perPage);
        }

       return $this->success(ErrorConst::SUCCESS_CODE_MSG, $product,true);

    }
 
}
